﻿using System;
using System.Collections.Generic;
using System.Linq;
using Smo = Microsoft.SqlServer.Management.Smo;

namespace BusinnesLogic.ServerObjects
{
    public class SqlDatabase : Database
    {
        #region Ctor

        public SqlDatabase(string databaseName, Smo.Server server)
            : base(databaseName)
        {
            // Create database in memory
            _Database = server.Databases[this.Name];

            // Fill the properties
            FillProperties();
        }

        #endregion

        #region Private Properties

        private Smo.Database _Database;
        private List<SqlTable> _SqlTables = null;

        #endregion    

        #region Private Methods

        private void FillProperties()
        {
            this.TableCount = _Database.Tables.Count;
            this._SqlTables = new List<SqlTable>();
        }

        #endregion

        #region Public Methods

        public override List<Table> Tables
        {
            get
            {
                if (_Database == null || _Database.Tables == null)
                    return null;
                else
                {
                    foreach (Smo.Table table in _Database.Tables)
                    {
                        SqlTable sqlTable = new ServerObjects.SqlTable(table.ToString(), _Database);

                        // Add table if is not a System table
                        if (!table.IsSystemObject)
                            _SqlTables.Add(sqlTable);
                    }

                    return _SqlTables.Cast<Table>().ToList();
                }

            }
        }

        public override Table this[int index]
        {
            get
            {
                Smo.Table table = _Database.Tables[index];

                if (table == null)
                    return null;
                else
                {
                    return this.Tables[index];
                }
            }

            set
            {
                Tables[index] = value;
            }
        }

        #endregion

    }
}
